#include "common_head.h"
#include "command.h"

/**
 * 处理客户端发送的 remove 请求
 * @param client_fd 套接字文件描述符
 * @param msg 用于存储命令及其参数的结构体指针
 * @param work_path 当前工作路径
 * @param user_name 当前用户的用户名
 * @param mysql MySQL 数据库连接
 */
void handler_remove(int client_fd, data *msg, char *work_path, char *user_name, MYSQL *mysql) {
    // 解析命令和路径
    char file_name[128] = {0};
    char file_work[128] = {0};
    char file_path[128] = {0};
    //路径和文件名之间添加/
    //strcpy(file_path,'/');
    //printf("file_path: %s\n", file_path);

    //mgs的args是file_path
    
    //strcpy(file_path, msg->args);
    //strcpy(file_path, "/" );
    strcat(file_path, msg->args);
    // 拼接SQL查询，查找并更新目标文件的删除状态
    char sql_buf[512] = {0};
    // 提取文件名
    strcpy(file_name, strrchr(file_path, '/') + 1);
    printf("file_name: %s\n", file_name);
    printf("file_path: %s\n", file_path);
    sprintf(sql_buf,
            "UPDATE file "
            "SET is_deleted = 1 "
            "WHERE file_name = '%s' "
            "AND file_path = '%s' "
            "AND user_id = (SELECT user_id FROM user WHERE user_name = '%s') "
            "AND is_deleted = 0",
            file_name, file_path, user_name);


    // 执行SQL语句
    if (mysql_query(mysql, sql_buf) == 0) {
        // 检查是否有行受到影响
        if (mysql_affected_rows(mysql) > 0) {
            log_log("INFO", "SERVER", "文件删除成功");
            strcpy(msg->command, "success");
        } else {
            log_log("ERROR", "SERVER", "文件未找到或已被删除");
            strcpy(msg->command, "failure");
        }
    } else {
        // SQL语句执行失败
        printf("SQL错误: %s\n", mysql_error(mysql));
        log_log("ERROR", "SERVER", "文件删除失败: SQL执行出错");
        strcpy(msg->command, "failure");
    }
    printf("file_name: %s\n", file_name);
    // 发送响应给客户端
    send(client_fd, msg, sizeof(data), 0);
    log_log("INFO", "SERVER", "文件删除成功");
}

